package com.example.template.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.alibaba.fastjson.JSONArray;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @className: JsonUtil
 * @description: Json工具类
 * @author: Li Chuanwei
 * @date: 2023/07/07 12:51
 * @Company: Copyright [日期] by [作者或个人]
 **/
@RequiredArgsConstructor
@Component
public class JsonUtil {
    private static ObjectMapper objectMapper = new ObjectMapper();

    static {
        JavaTimeModule timeModule = new JavaTimeModule();
        // 设置LocalDateTime的序列化格式
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        timeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(dateTimeFormatter));
        objectMapper.registerModule(timeModule);
    }

    public static String obj2String(Object object) {
        String res = null;
        try {
            res = objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return res;
    }


    public static List<String> parseArray(String jsonArray) {
        return JSONArray.parseArray(jsonArray, String.class);
    }

}
